package com.github.netty.server;


import com.github.netty.config.IServerConfig;
import com.github.netty.properties.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author ArchieSean
 * @description netty启动初始化类
 * @date 2024-08-11
 */
public class NettyServer implements DisposableBean {
    private static final Log logger = LogFactory.getLog(NettyServer.class);
    @Autowired
    private NettyProperties properties;

    @Autowired
    private IServerConfig configurer;

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;




    /**
     * 用于开启netty服务
     */
    public void startNettyServer() {
        //创建主线程组
       this.bossGroup = new NioEventLoopGroup(1);
        //工作组
       this.workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            configurer.configurePipeline(pipeline);
                        }
                    });

            //配置bootstrap
            configurer.config(bootstrap);
            ChannelFuture future = bootstrap.bind(properties.getPort()).sync();
            logger.info("-----Netty server 启动成功，端口"+properties.getPort()+"------");
            //扩展点，保留自旋扩展
            configurer.extendPower(future);
            future.channel().closeFuture().sync();
        }catch (Exception ex){
            logger.error("====netty server启动异常====");
           throw new RuntimeException(ex.getLocalizedMessage());
        }
    }

    /**
     * 容器销毁时调用
     */
    @Override
    public void destroy() {
        this.workerGroup.shutdownGracefully();
        this.bossGroup.shutdownGracefully();
    }
}
